package com.zjdiepu.www.biz.dz;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.SysParamsType;
import com.zjdiepu.www.biz.helper.ServiceHelper;
import com.zjdiepu.www.commpent.mapper.dh.DzRegistrationVoMapper;
import com.zjdiepu.www.dao.dz.DzRegistrationMapper;
import com.zjdiepu.www.dao.other.OtherWantWarningMapper;
import com.zjdiepu.www.dao.system.BaseCustomerMapper;
import com.zjdiepu.www.dao.system.BaseSalersmanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessCarMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.ibiz.dz.IDzRegistrationService;
import com.zjdiepu.www.ibiz.other.IOtherWarningConfigurationService;
import com.zjdiepu.www.ibiz.system.IBaseSysParamsService;
import com.zjdiepu.www.ibiz.system.IOtherHolidaysService;
import com.zjdiepu.www.ibiz.zpp.SystemService;
import com.zjdiepu.www.model.dz.dto.DzRegistration;
import com.zjdiepu.www.model.dz.ext.DzRegistrationExt;
import com.zjdiepu.www.model.other.dto.OtherMessageApp;
import com.zjdiepu.www.model.other.dto.OtherWantWarning;
import com.zjdiepu.www.model.other.dto.OtherWarningConfiguration;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 车牌登记Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月10日 12时42分<br/>
 * @since 1.0<br/>
 */
@Service
public class DzRegistrationServiceImpl extends BaseService implements IDzRegistrationService {
	public static final Logger logger = LoggerFactory.getLogger(DzRegistrationServiceImpl.class);

	@Autowired
	private DzRegistrationMapper dzRegistrationMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private OtherWantWarningMapper otherWantWarningMapper;
	@Autowired
	private ServiceHelper serviceHelper;
	@Autowired
	private IBaseSysParamsService baseSysParamsService;
	@Autowired
	private IOtherHolidaysService otherHolidaysService;
	@Autowired
	private IOtherWarningConfigurationService otherWarningConfigurationService;
	@Autowired
	private BaseCustomerMapper baseCustomerMapper;
	@Autowired
	private BaseSalersmanMapper baseSalersmanMapper;
	@Autowired
	private YwBusinessCarMapper ywBusinessCarMapper;
	@Autowired
	private DzRegistrationVoMapper dzRegistrationVoMapper;
	@Autowired
	private SystemService systemService;
	

	@Override
	public ApiResponse saveRegistrationPlates(DzRegistration dzRegistration,
			AbstractSysUser currentUser) {
		if(!dzRegistration.isCompleted()) {
			return ApiResponse.fail(901, "车牌登记信息不完整");
		}
//		if(StringUtils.isNotBlank(dzRegistration.getId())) {
//			return ApiResponse.fail(999, "车牌登记信息不能修改");
//		}
		if(StringUtils.isNotBlank(dzRegistration.getId())) {
			dzRegistration.initUpdateData(currentUser.getId(), currentUser.getName());
			dzRegistrationMapper.updateByPrimaryKeySelective(dzRegistration);
		} else {
			dzRegistration.initInsertData(currentUser.getId(), currentUser.getName());
			dzRegistrationMapper.insert(dzRegistration);
		}
	    
	    String busiId = dzRegistration.getBusiId();
	    
	    YwBusinessCar ywBusinessCar = new YwBusinessCar();
	    ywBusinessCar.setDpStatus(DpStatus.NORMAL.getCode());
	    ywBusinessCar.setBusiId(busiId);
	    ywBusinessCar = ywBusinessCarMapper.selectRefined(ywBusinessCar);
	    if(ywBusinessCar != null) {
	    	dzRegistrationVoMapper.mapper(dzRegistration);
	    	String regionRegistration = dzRegistration.getRegionRegistration();
	    	if(StringUtils.isNotBlank(regionRegistration)) {
	    		ywBusinessCar.setRegistrationArea(regionRegistration);
	    	}
	    	ywBusinessCarMapper.updateByPrimaryKeySelective(ywBusinessCar);
	    }
	    
		YwBusiness ywBusiness = new YwBusiness();
		ywBusiness.setId(busiId);
//		ywBusiness.setBusiStatus(BusiStatus.CHE_PAI_YI_DENG_JI.getCode());
		ywBusiness.setLicensePlateTime(dzRegistration.getDateRegistrationNow());
		ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		
		YwBusiness dbYwBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
		if(null == dbYwBusiness) {
			return ApiResponse.fail(901, "业务记录不存在或已经被删除");
		}
		String customerName = dbYwBusiness.getCustomerName();
//		String customerId = dbYwBusiness.getCustomerId();
		String salesmanId = dbYwBusiness.getSalesmanId();
		
		//删除车牌注册预警信息
		OtherWantWarning otherWantWarning = new OtherWantWarning();
		otherWantWarning.setBusiId(dzRegistration.getBusiId());
		otherWantWarning.setModeId(ModeIDType.SP.getCode());
		otherWantWarningMapper.deletedReal(otherWantWarning);
		
		//抵押提示
//		OtherMessageApp otherMessageApp_ = new OtherMessageApp();
//		otherMessageApp_.setModeId(ModeIDType.DY.getCode());
//		otherMessageApp_.setBusiId(busiId);
//		otherMessageApp_.setDataid(dzRegistration.getId());
//		otherMessageApp_.setTypeMsg("01");
//		otherMessageApp_.setTypeMsgEvent("24");
//		otherMessageApp_.setNotificationBar("客户" + customerName + "的订单，请及早办理抵押");
//		otherMessageApp_.setTitle("客户" + customerName + "的订单，请及早办理抵押");
//		otherMessageApp_.setContent("提示：客户" + customerName + "的订单，请及早办理抵押");
//		Date now = new Date();
//		otherMessageApp_.setTimeCreate(now);
//		otherMessageApp_.setTimeSend(now);
//		otherMessageApp_.setStatusMsg(MessageStatus.WEI_TUI_SONG.getCode());
//		
//		String shortMessage_ = "提示：客户" + customerName + "的订单，请及早办理抵押";
//		serviceHelper.saveMsg(otherMessageApp_, salesmanId, customerName, shortMessage_, currentUser, logger);
		
		systemService.diepuNewsHandle(currentUser, ModeIDType.DY.getCode(), "24", busiId, null);
		
		//抵押预警
		OtherWantWarning otherWantWarning_ = new OtherWantWarning();
		otherWantWarning_.initInsertData(currentUser.getId(), currentUser.getName());
		otherWantWarning_.setModeId(ModeIDType.DY.getCode());
		otherWantWarning_.setBusiId(busiId);
		otherWantWarning_.setDataid(dzRegistration.getId());
		otherWantWarning_.setTypeMsg("03");
		otherWantWarning.setTypeMsgEvent("25");
		//预警时间
		//获取地区配置================
		OtherWarningConfiguration otherWarningConfiguration = otherWarningConfigurationService.getOtherWarningConfigurationBySalesmanId(SysParamsType.DI_YA_CHAO_QI_YU_JING.getCode(), salesmanId);
		Integer warningDay = null;
		if(null != otherWarningConfiguration){
			warningDay = otherWarningConfiguration.getWarningDay();
		}
		
		//获取系统参数配置================
		if(null == warningDay) {
			String paramValue = baseSysParamsService.getValueByCode(SysParamsType.DI_YA_CHAO_QI_YU_JING.getCode());
			if(StringUtils.isNotBlank(paramValue)) {
				warningDay = Integer.valueOf(paramValue);
			}
		}
		
		//获取默认配置================
		if(null == warningDay) {
			warningDay = (Integer)SysParamsType.DI_YA_CHAO_QI_YU_JING.getDefaultValue();
		}
		
		if(null == warningDay) {
			ExceptionHelper.thow("9999", "没有配置抵押预警时间");
		}
		
		Date nextWorkDate = otherHolidaysService.getNextWorkDate(new Date(), "1", warningDay);
		otherWantWarning_.setTimeWarning(nextWorkDate);
		otherWantWarning_.setStatusMsg(1);
		
		OtherMessageApp spAlertMsg = new OtherMessageApp();
		spAlertMsg.setModeId(ModeIDType.DY.getCode());
		spAlertMsg.setBusiId(busiId);
		spAlertMsg.setDataid(dzRegistration.getId());
		spAlertMsg.setTypeMsg("03");
		spAlertMsg.setTypeMsgEvent("25");
		spAlertMsg.setNotificationBar("客户" + customerName + "的订单 请尽快办理抵押");
		spAlertMsg.setTitle("客户" + customerName + "的订单 请尽快办理抵押");
		spAlertMsg.setContent("预警：客户" + customerName + "的订单 请尽快办理抵押");
		spAlertMsg.setTimeCreate(new Date());
		String tcShortMessage = "预警：客户" + customerName + "的订单 请尽快办理抵押";
		serviceHelper.saveAlert(otherWantWarning_, spAlertMsg, salesmanId, customerName, tcShortMessage, currentUser);
		return ApiResponse.success(dzRegistration.getId());
	}
	
	
	@Override
	public void saveUpdateAndDelete(DzRegistration dzRegistration, OperateType operType) {
		switch (operType) {
		case add:
			dzRegistration.initInsertData(dzRegistration.getModifier(), dzRegistration.getModifierName());
			dzRegistrationMapper.insert(dzRegistration);
			break;
		case edit:
			dzRegistration.initUpdateData(dzRegistration.getModifier(), dzRegistration.getModifierName());
			// 影响的记录数
			int updateCount = dzRegistrationMapper.updateByPrimaryKeySelective(dzRegistration);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			dzRegistration.initDeleteData(dzRegistration.getModifier(), dzRegistration.getModifierName());
			// 影响的记录数
			int deleteCount = dzRegistrationMapper.updateByPrimaryKeySelective(dzRegistration);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<DzRegistration> selectByExt(DzRegistrationExt dzRegistrationExt) {
		return dzRegistrationMapper.selectByExt(dzRegistrationExt);
	}
	
	@Override
	public int countByExt(DzRegistrationExt dzRegistrationExt){
		return dzRegistrationMapper.countByExt(dzRegistrationExt);
	}
	
	@Override
	public DzRegistration selectById(String id) {
		return dzRegistrationMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			dzRegistrationMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(DzRegistration dzRegistration) {
		return dzRegistrationMapper.countRefined(dzRegistration);
	}

	@Override
	public DzRegistration selectRefined(DzRegistration dzRegistration) {
		return dzRegistrationMapper.selectRefined(dzRegistration);
	}
	
	@Override
	public int deletedRefined(DzRegistration dzRegistration) {
		return dzRegistrationMapper.deletedRefined(dzRegistration);
	}

	@Override
	public boolean repeat(DzRegistration dzRegistration) {
		int count = countRefined(dzRegistration);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(dzRegistration.getId())) {
			return true;
		}
		DzRegistration dbItem = selectRefined(dzRegistration);
		if(null == dbItem) {
			return false;
		}
		return !dzRegistration.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return dzRegistrationMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<DzRegistration> dzRegistrations) {
		return dzRegistrationMapper.insertBatch(dzRegistrations);
	}
}
